package com.mystore.framework.mail;

import com.mystore.framework.mail.page.IMailPage;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailSessionBean {
    private String hostUrl;
    private String password;
    private Session session;
    private Authenticator auth;
    private Properties props;

    public void sendMail(String email, String subject, IMailPage mailPage) throws MessagingException {
        //创建配置文件
        props = new Properties();
        //设置发送时遵从SMTP协议
        props.setProperty("mail.transport.protocol", "SMTP");
        /*
         * 发送邮件的域名
         * smtp.163.com则代表发送邮件时使用的邮箱域名来自163
         */
        props.setProperty("mail.host", "smtp.163.com");
        //设置用户的认证方式auth
        props.setProperty("mail.smtp.auth", "true");
        auth = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                //return new PasswordAuthentication("用户名", "密码");
                //注意qq邮箱需要去qq邮箱的设置中获取授权码，并将授权码作为密码来填写
                return new PasswordAuthentication(hostUrl, password);
            }
        };
                //创建session域
        session= Session.getDefaultInstance(props,auth);
        Message message = new MimeMessage(session);
        //设置邮件发送者,与PasswordAuthentication中的邮箱一致即可
        message.setFrom(new InternetAddress(hostUrl));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
        //设置邮件主题
        message.setSubject(subject);
        //设置邮件内容
        message.setContent(mailPage.toString(), "text/html;charset=utf-8");
        //发送邮件
        Transport.send(message);
    }

    public String getHostUrl() {
        return hostUrl;
    }

    public void setHostUrl(String hostUrl) {
        this.hostUrl = hostUrl;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public MailSessionBean(String hostUrl, String password) {
        this.hostUrl = hostUrl;
        this.password = password;
    }

    public MailSessionBean() {

    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public Authenticator getAuth() {
        return auth;
    }

    public void setAuth(Authenticator auth) {
        this.auth = auth;
    }

    public Properties getProps() {
        return props;
    }

    public void setProps(Properties props) {
        this.props = props;
    }
}


